﻿using MediatR;
using NPOI.SS.Formula.Functions;
using S.Authorization.Common;
using S.Authorization.Common.Dto;
using S.Authorization.Domain.Model.Organization;
using S.Authorization.Infrastructure.Interface.Organization;
using S.Authorization.Read.API.Application.Command.OrganizationCommand;

namespace S.Authorization.Read.API.Application.CommandHandlers.OrganizationCommandHandler
{
    public class FieldModeCommandHandler : IRequestHandler<FieldModeCommand, List<SelectDto>>,IRequestHandler<FielModelByIdCommand,Pager<FieldModel>>
    {
        private readonly IFieldModelRepository  field;
        public FieldModeCommandHandler(IFieldModelRepository _field)
        {
            this.field = _field;
        }
        public async Task<List<SelectDto>> Handle(FieldModeCommand request, CancellationToken cancellationToken)
        {
            List<FieldModel> childList = field.GetAllAsync().Result;
            List<SelectDto> children = childList.Select(x => new SelectDto
            {
                value = x.ColumnManagementId,
                label = x.ColumnName,
            }).ToList();
            return children;
        }
        /// <summary>
        /// 根据栋舍主键返填栏位
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Pager<FieldModel>> Handle(FielModelByIdCommand request, CancellationToken cancellationToken)
        {
            int TotalCount = 0;
            int PageCount = 0;
            var list = field.GetAllAsync().Result.Where(x => x.BuildingManagementId == request.BuildingManagementId).ToList();
            TotalCount= list.Count;
            PageCount = (int)Math.Ceiling((TotalCount * 1.0) / request.PageSize);
            list = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return new Pager<FieldModel>()
            {
                TotalCount = TotalCount,
                PageCount = PageCount,
                resultData = list
            };
        }
    }
}
